/*+***********************************************************************************
 Filename: 03_tinycore_step05\src\peripheral_uart.v
 Description: a simple uart peripheral module.

 Modification:
   2022.11.08 Creation   H.Zheng

Copyright (C) 2022  Zheng Hui (hzheng@gzhu.edu.cn)

License: MulanPSL-2.0

***********************************************************************************-*/

module peripheral_uart (
    input wire clk,
    input wire reset_n,
    input wire rxd,
    output wire txd,
    input wire ce, //chip enable
    input wire wre, //write enable
    input wire [1:0] addr, //address bus
    input wire [31:0] data_in,
    output wire [31:0] data_out

);

    reg [31:0] data_tx_reg;

    wire uart_tx_en = ce & wre & (addr==2'b00);

    //write data_tx_reg register
    always @(posedge clk) begin
        if (~reset_n) begin
            data_tx_reg <= 32'b0;
        end
        else if (uart_tx_en) begin
            data_tx_reg <= data_in;
        end
    end    

    //generate tx pulse
    reg [1:0] shift_reg;
    always @(posedge clk) begin
        if (~reset_n) begin
            shift_reg <= 2'b0;
        end
        else begin
            shift_reg <= {shift_reg[0], uart_tx_en};
        end
    end    
    wire uart_tx_en_pulse = (shift_reg[1] == 0) & (shift_reg[0] == 1);
    
    //Baudrate=115200; DIVIDER=27,000,000/115200=234.375
    uart_tx #(.BAUDRATE_DIVIDER(234)) u_uart0_tx(  
       .clk(clk),  //27MHz
       .reset_n(reset_n),
       .tx_en(uart_tx_en_pulse),
       .tx_data(data_tx_reg[7:0]),
       .txd(txd)
    );


    //
    assign data_out = 32'b0;

endmodule
